<%@ page import="com.example.dao.ProductDao" %>
<%@ page import="com.example.domain.Product" %>
<%@ page import="com.example.util.DBUtil" %>
<%@ page import="java.util.Optional" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    int productId = 0;
    try {
        productId = Integer.parseInt(request.getParameter("id"));
    } catch (NumberFormatException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的商品ID");
        return;
    }

    try {
        ProductDao productDao = new ProductDao();
        Optional<Product> productOptional = productDao.getProductById(productId);
        
        if (productOptional.isPresent()) {
            Product product = productOptional.get();
            request.setAttribute("product", product);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "商品不存在");
            return;
        }
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "加载商品信息失败: " + e.getMessage());
        return;
    }
%>
<!DOCTYPE html>
<html>
<head>
    <title>商品详情</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
</head>
<body>
    <!-- 导航栏 -->
    <nav class="header-nav">
        <div class="nav-container">
            <a href="../index.jsp" class="nav-brand">购物网</a>
            
            <ul class="nav-links">
                <li><a href="../index.jsp">首页</a></li>
                <li><a href="list.jsp">商品浏览</a></li>
                <li><a href="../cart/view/cart.jsp">购物车</a></li>
            </ul>
            
            <div class="user-actions">
                <% if (session.getAttribute("user") != null) { %>
                    <a href="../admin/layout.jsp" class="btn btn-outline">后台管理</a>
                    <a href="../auth/logout.jsp" class="btn" style="margin-left: 10px;">退出</a>
                <% } else { %>
                    <a href="../auth/login.jsp" class="btn btn-outline">登录</a>
                    <a href="../auth/register.jsp" class="btn" style="margin-left: 10px;">注册</a>
                <% } %>
            </div>
        </div>
    </nav>
    
    <div class="container">
        <div class="page-title">
            <h1>商品详情</h1>
        </div>
        
        <jsp:useBean id="product" scope="request" type="com.example.domain.Product"/>
        
        <div class="product-detail">
            <div class="product-image">
                <% if (product.getLogo() != null && !product.getLogo().isEmpty()) { %>
                    <img src="../<%= product.getLogo() %>" alt="<%= product.getProduct_name() %>" style="max-width: 300px; height: auto;">
                <% } else { %>
                    <img src="../assets/images/no-image.svg" alt="暂无图片" style="max-width: 300px; height: auto; opacity: 0.5;">
                <% } %>
            </div>
            
            <div class="product-info">
                <h2><%= product.getProduct_name() %></h2>
                <p class="price">
                    <% if (product.getSale_price() > 0) { %>
                        <span class="sale-price">¥<%= product.getSale_price() %></span>
                        <span class="original-price">¥<%= product.getPrice() %></span>
                    <% } else { %>
                        ¥<%= product.getPrice() %>
                    <% } %>
                </p>
                <p class="status">
                    状态: <%= product.getStatus() == 1 ? "正常" : "下架" %>
                </p>
                <p class="type">
                    类型ID: <%= product.getType_id() %>
                </p>
                <% if (product.getIs_top() == 1) { %>
                    <p class="top">推荐商品</p>
                <% } %>
                <div class="intro">
                    <h3>商品介绍</h3>
                    <p><%= product.getIntro() != null ? product.getIntro() : "暂无介绍" %></p>
                </div>
                <div class="actions">
                    <button class="btn btn-success" onclick="addToCart(<%= product.getId() %>)">加入购物车</button>
                    <button class="btn" onclick="history.back()">返回</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        function addToCart(productId) {
            // 检查用户是否已登录
            <% if (session.getAttribute("user") == null) { %>
                if (confirm("您需要先登录才能添加商品到购物车，是否前往登录？")) {
                    window.location.href = '../auth/login.jsp';
                }
                return;
            <% } %>
            
            // 发送 AJAX 请求添加到购物车
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '../cart/api/add.jsp', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        if (xhr.responseText === 'success') {
                            alert('商品已添加到购物车');
                        } else {
                            alert('添加失败: ' + xhr.responseText);
                        }
                    } else {
                        alert('网络错误，请稍后重试');
                    }
                }
            };
            xhr.send('productId=' + productId);
        }
    </script>
</body>
</html>